import React, { useState, useEffect } from 'react';
import {
  Modal,
  Input,
  List,
  Card,
  Tag,
  Button,
  Space,
  Typography,
  Empty,
  Spin,
  message,
  Avatar,
  Row,
  Col
} from 'antd';
import {
  SearchOutlined,
  FileOutlined,
  DownloadOutlined,
  EyeOutlined,
  LikeOutlined,
  ArrowUpOutlined,
  UserOutlined,
  ClockCircleOutlined
} from '@ant-design/icons';
import { torrents } from '../../services';

const { Search } = Input;
const { Text, Paragraph } = Typography;

const ResourceSelector = ({
  visible,
  onCancel,
  onSelect,
  selectedResource
}) => {
  const [loading, setLoading] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [resourcesList, setResourcesList] = useState([]);
  const [allResources, setAllResources] = useState([]);
  const [currentSelection, setCurrentSelection] = useState(selectedResource);

  // 加载所有资源
  useEffect(() => {
    if (visible) {
      loadAllResources();
    }
  }, [visible]);

  const loadAllResources = async () => {
    try {
      setLoading(true);
      console.log('📥 加载资源广场数据用于选择...');

      const response = await torrents.getAllUploadedTorrents();

      if (response.success) {
        const rawTorrents = response.data.torrents || [];

        // 适配数据格式
        const adaptedTorrents = rawTorrents.map(torrent => ({
          id: torrent.id || Math.random().toString(36).substr(2, 9),
          title: torrent.name || torrent.title || '未命名种子',
          category: torrent.classification || '未分类',
          classification: torrent.classification || '未分类',
          uploader: torrent.uploader || '匿名用户',
          uploadDate: torrent.fileTimestamps || torrent.uploadDate,
          seeders: torrent.seeder || 0,
          downloads: torrent.download || 0,
          likes: torrent.upvote || 0,
          size: torrent.size || '未知大小',
          description: torrent.comment || '暂无描述',
          coverImage: torrent.presource || torrent.pResource || 'https://via.placeholder.com/100x150',
          torrentUrl: torrent.tresource || torrent.tResource || null,
          hash: torrent.hash || null,
          promotion: torrent.category && torrent.category !== null ? torrent.category : 'none',
          detailUrl: `/torrent/${torrent.id || torrent.hash || Math.random().toString(36).substr(2, 9)}`
        }));

        setAllResources(adaptedTorrents);
        setResourcesList(adaptedTorrents);

        message.success(`加载了 ${adaptedTorrents.length} 个资源`);
      } else {
        message.error('加载资源失败');
      }
    } catch (error) {
      console.error('❌ 加载资源失败:', error);
      message.error('加载资源失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 搜索资源
  const handleSearch = (value) => {
    setSearchKeyword(value);

    if (!value.trim()) {
      setResourcesList(allResources);
      console.log('🔍 显示所有资源:', allResources.length);
      return;
    }

    const keyword = value.toLowerCase().trim();
    const filteredResources = allResources.filter(resource =>
      resource.title?.toLowerCase().includes(keyword) ||
      resource.category?.toLowerCase().includes(keyword) ||
      resource.description?.toLowerCase().includes(keyword) ||
      resource.uploader?.toLowerCase().includes(keyword)
    );

    setResourcesList(filteredResources);
    console.log(`🔍 搜索 "${value}" 找到 ${filteredResources.length} 个资源`);
  };

  // 选择资源
  const handleSelectResource = (resource) => {
    setCurrentSelection(resource);
    console.log('✅ 选择资源:', resource.title);
  };

  // 确认选择
  const handleConfirmSelection = () => {
    if (!currentSelection) {
      message.warning('请选择一个资源');
      return;
    }

    // 构造资源信息返回给父组件
    const resourceInfo = {
      id: currentSelection.id,
      title: currentSelection.title,
      category: currentSelection.category,
      uploader: currentSelection.uploader,
      detailUrl: currentSelection.detailUrl,
      // 生成友好的显示链接
      displayUrl: `/torrent/${currentSelection.id}`,
      resourceData: currentSelection
    };

    onSelect(resourceInfo);
    message.success(`已选择资源: ${currentSelection.title}`);
  };

  // 格式化文件大小
  const formatSize = (sizeStr) => {
    if (!sizeStr || sizeStr === '未知大小') return '未知大小';
    return sizeStr;
  };

  // 格式化时间
  const formatTime = (dateStr) => {
    if (!dateStr) return '未知时间';
    try {
      const date = new Date(dateStr);
      return date.toLocaleDateString('zh-CN');
    } catch {
      return '未知时间';
    }
  };

  return (
    <Modal
      title="选择资源链接"
      open={visible}
      onCancel={onCancel}
      width={800}
      style={{ top: 20 }}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button
          key="confirm"
          type="primary"
          onClick={handleConfirmSelection}
          disabled={!currentSelection}
        >
          确认选择
        </Button>
      ]}
    >
      <div style={{ marginBottom: 16 }}>
        <Search
          placeholder="搜索资源标题、分类、描述或上传者"
          enterButton={<SearchOutlined />}
          size="large"
          onSearch={handleSearch}
          onChange={e => {
            if (!e.target.value) {
              handleSearch('');
            }
          }}
          allowClear
        />
      </div>

      {currentSelection && (
        <Card
          size="small"
          style={{ marginBottom: 16, background: '#f0f9ff', border: '1px solid #1890ff' }}
          title={
            <Text strong style={{ color: '#1890ff' }}>
              当前选择: {currentSelection.title}
            </Text>
          }
        >
          <Space>
            <Tag color="blue">{currentSelection.category}</Tag>
            <Text type="secondary">
              <UserOutlined /> {currentSelection.uploader}
            </Text>
            <Text type="secondary">
              大小: {formatSize(currentSelection.size)}
            </Text>
          </Space>
        </Card>
      )}

      <div style={{ maxHeight: 400, overflowY: 'auto' }}>
        <Spin spinning={loading}>
          {resourcesList.length === 0 && !loading ? (
            <Empty
              description={searchKeyword ? `未找到包含 "${searchKeyword}" 的资源` : "暂无资源"}
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          ) : (
            <List
              dataSource={resourcesList}
              renderItem={(resource) => (
                <List.Item
                  style={{
                    cursor: 'pointer',
                    backgroundColor: currentSelection?.id === resource.id ? '#e6f7ff' : 'transparent',
                    border: currentSelection?.id === resource.id ? '1px solid #1890ff' : '1px solid transparent',
                    borderRadius: 8,
                    marginBottom: 8,
                    padding: 12,
                    transition: 'all 0.3s'
                  }}
                  onClick={() => handleSelectResource(resource)}
                >
                  <Row style={{ width: '100%' }} gutter={16}>
                    <Col span={4}>
                      <Avatar
                        shape="square"
                        size={64}
                        src={resource.coverImage}
                        icon={<FileOutlined />}
                      />
                    </Col>
                    <Col span={20}>
                      <div>
                        <div style={{ marginBottom: 8 }}>
                          <Text strong style={{ fontSize: 16 }}>
                            {resource.title}
                          </Text>
                          {currentSelection?.id === resource.id && (
                            <Tag color="blue" style={{ marginLeft: 8 }}>已选择</Tag>
                          )}
                        </div>

                        <div style={{ marginBottom: 8 }}>
                          <Space wrap>
                            <Tag color="green">{resource.category}</Tag>
                            <Text type="secondary">
                              <UserOutlined /> {resource.uploader}
                            </Text>
                            <Text type="secondary">
                              <ClockCircleOutlined /> {formatTime(resource.uploadDate)}
                            </Text>
                          </Space>
                        </div>

                        <Paragraph
                          ellipsis={{ rows: 2 }}
                          style={{ marginBottom: 8, color: '#666' }}
                        >
                          {resource.description}
                        </Paragraph>

                        <Space>
                          <Text type="secondary">
                            <ArrowUpOutlined /> {resource.seeders} 做种
                          </Text>
                          <Text type="secondary">
                            <DownloadOutlined /> {resource.downloads} 下载
                          </Text>
                          <Text type="secondary">
                            <LikeOutlined /> {resource.likes} 点赞
                          </Text>
                          <Text type="secondary">
                            大小: {formatSize(resource.size)}
                          </Text>
                        </Space>
                      </div>
                    </Col>
                  </Row>
                </List.Item>
              )}
            />
          )}
        </Spin>
      </div>

      <div style={{ marginTop: 16, padding: 8, background: '#f5f5f5', borderRadius: 4 }}>
        <Text type="secondary" style={{ fontSize: 12 }}>
          💡 提示: 选择资源后，广播中将包含该资源的详情页面链接，用户可以直接跳转查看和下载资源。
        </Text>
      </div>
    </Modal>
  );
};

export default ResourceSelector;
